package com.simple.mipc.messager;

import android.os.Bundle;
import android.util.Log;

import com.simple.mipc.annotation.OnApply;
import com.simple.mipc.entity.Executor;
import com.simple.mipc.utils.ClassUtil;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExecutorManager extends HashMap<String, Executor> {

    private static final String TAG = ExecutorManager.class.getName();

    private static ExecutorManager executorManager = new ExecutorManager();

    private ExecutorManager() {

    }

    public static ExecutorManager getInstance() {
        if (Objects.isNull(executorManager)) {
            executorManager = new ExecutorManager();
        }
        return executorManager;
    }

    /**
     * 服务器端，使用该方法，对对外开放的功能，进行注册
     * @param instance 对外服务的方法，所在类的实例
     */
    public void registerFunc(Object instance) {
        Method[] methods = ClassUtil.getMethods(instance);
        Arrays.stream(methods).filter(method -> {
            OnApply onApply = method.getDeclaredAnnotation(OnApply.class);
            if (Objects.isNull(onApply)) {
                Log.i(TAG, String.format("方法：%s，没有找到注解：%s，不是开放的方法", method.getName(), OnApply.class));
                return false;
            }
            return true;
        }).forEach(method -> {
            Executor executor = new Executor(method, instance);
            put(executor.getRes(), executor);
        });
    }

    public <T> T executor(String res, Bundle bundle) {
        Executor executor = get(res);
        if (Objects.isNull(executor)) {
            return (T) "不是对外服务的功能";
        }
        assert executor != null;
        return executor.execute(bundle);
    }
}
